local ClientOHOH = _G.ClientOHOH;

local M = ClientOHOH.class.new(script, ClientOHOH.files.BaseObject())
local CallBackManager = ClientOHOH.load.CallBackManager();
local ConnectClass=_G.CommonOHOH.load.Connect();
local PetTool=_G.CommonOHOH.load.PetTool();
ClientOHOH.load.PetCell()

local instStr={
	cell = "ctrl.petList.petCopy",
	petList = "ctrl.petList.peListtFrame",
	voidTime = "ctrl.content.time",

	craftBtn ="ctrl.content.btn",
	content="ctrl.content.contentFrame" ,
	copy = "ctrl.slotlist.copy",

	viewportFrame= "ctrl.slotlist.ViewportFrame"
}

function M.new(...)
	return M(...);
end;

function M.ctor(self,ctrl)
	M.super.ctor(self);
	self.ctrl=ctrl
	self.List={}
	self.ui=ctrl:InitUiInst2(ctrl.main_inst,instStr)
	self.ui.cell.Visible=false
	self.SelectedCell = nil

	self.ui.content.Visible = false
	self.ui.petList.Visible = false
	self:AddConnect()
	CallBackManager:AddRbxConnect(self,self.ui.craftBtn.Activated, function()
		self.ctrl.CraftClickEvent:Action(self.SelectedCell.petId)
		self.ui.content.Visible = false
		self.ui.petList.Visible = false
		--移除选中宠物，更新List的代码
		--self.ctrl.UpdateSlotList(self.SelectedCell.petId)
		self.ui.copy.Parent.Visible = true

	end);
end;
function M.AddConnect(self)
	self.ctrl.DatabaseReadyEvent:Connect(function()
        self.database = self.ctrl:GetDataBase()
		local data=self.database:GetData("pets")
		self:UpdateCell(data.had)
    end)
end;
function M.dtor(self)
	M.super.dtor(self);
end;

function M.GetGuid(self,petId,index)
	return petId.."_"..index
end

function M.CreateCell(self,guid,petId) 
	local cell = ClientOHOH.load.PetCell().new(petId,guid,self.ui.cell.Parent,self.ctrl:GetDataBase())
	cell.ClickEvent:Connect(function()
		self.ctrl:CellClick(cell)
	end)
	return cell
end
function M.Change(self,cell)

	if self.SelectedCell == nil then
		self.SelectedCell = cell
		cell:SetSelectedStatus(true)	
		self.ctrl.insts.craftBtn.Visible = true
		return
	end

	if self.SelectedCell == cell then
		self.SelectedCell = nil
		cell:SetSelectedStatus(false)
		self.ctrl.insts.craftBtn.Visible = false
	else
		self.SelectedCell:SetSelectedStatus(false)
		cell:SetSelectedStatus(true)
		self.SelectedCell = cell
		self.ctrl.insts.craftBtn.Visible = true
	end

end




function M.HideAllCell(self)
	for  _,cell in pairs(self.List) do
        cell:ClearMouseEnter(nil)
	end
end




---------------------------- 公共函数----------------------------------------------
function M.UpdateCell(self,data)
	local had={} --记录已经拥有的
	for  petId,count in pairs(data) do
		for i=1,count do
			local guid=self:GetGuid(petId,i)
			had[guid]=true
			if  not self.List[guid] and PetTool.IsCanVoid(petId) then --不存在，需要创建新的
				self.List[guid]=self:CreateCell(guid,petId)
			end
		end
	end

	for guid,cell in pairs(self.List) do
		if not had[guid] then --不存在
			cell:dtor() --销毁
			self.List[guid]=nil
		end
	end

end

return M